package com.rxy.sqlSession;

import com.rxy.config.BoundSql;
import com.rxy.pojo.Configuration;
import com.rxy.pojo.MapperStatement;
import com.rxy.util.GenericTokenParser;
import com.rxy.util.ParameterMapping;
import com.rxy.util.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    private Connection connection = null;

    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... param) throws Exception {
        //1.注册驱动，获取连接
        connection = configuration.getDataSource().getConnection();
        //2.获取sql语句: select * from user where id = #{id} and username = #{username}
        String sql = mapperStatement.getSql();
        //转换sql语句：select * from user where id = ? and username = ?
        //转换的过程中，还需要对#{}里面的值进行解析存储
        BoundSql boundSql = getBoundSql(sql);
        //3.获取预处理对象：prepareStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //4.设置参数
        Class<?> paramterTypeClass = mapperStatement.getParamterType(); //参数类型
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            //反射获取字段值
            Field field = paramterTypeClass.getDeclaredField(content);
            field.setAccessible(true);
            Object object = field.get(param[0]);
            //设置参数
            preparedStatement.setObject(i+1, object);
        }
        //5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        //6.封装返回结果集
        Class<?> resultTypeClass = mapperStatement.getResultType();
        ArrayList<Object> objects = new ArrayList<>();
        while(resultSet.next()){
            Object o = resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名：下标从1开始
                String columnName = metaData.getColumnName(i);
                //字段的值
                Object value = resultSet.getObject(columnName);
                //使用内省或者(反射)，根据数据库表和实体的对应关系，完成封装
                //创建属性描述器，为属性生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                //获取写方法，向类中写入值
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            objects.add(o);
        }
        return (List<E>) objects;
    }

    @Override
    public int update(Configuration configuration, MapperStatement mapperStatement, Object... param) throws Exception {
        //1.注册驱动，获取连接
        connection = configuration.getDataSource().getConnection();
        //2.获取sql语句
        String sql = mapperStatement.getSql();
        //转换sql语句
        BoundSql boundSql = getBoundSql(sql);
        //3.获取预处理对象：prepareStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //4.设置参数
        Class<?> paramterTypeClass = mapperStatement.getParamterType(); //参数类型
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        if(isBaseType(paramterTypeClass)){
            preparedStatement.setObject(1, param[0]);
        }else{
            for (int i = 0; i < parameterMappingList.size(); i++) {
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                String content = parameterMapping.getContent();
                //反射获取字段值
                Field field = paramterTypeClass.getDeclaredField(content);
                field.setAccessible(true);
                Object object = field.get(param[0]);
                //设置参数
                preparedStatement.setObject(i+1, object);
            }
        }
        //5.执行sql
        int ret = preparedStatement.executeUpdate();
        return ret;
    }

    @Override
    public void close() throws SQLException {
        if(connection != null) connection.close();
    }

    /**
     * 完成对#{}的解析工作：1.将#{}使用?进行替代，2.解析出#{}里面的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类，配合通用标记解析器GenericTokenParser来完成对配置文件等的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        //GenericTokenParser:通用的标记解析处理器，完成了代码片段中的占位符解析
        //然后再根据给定的标记处理器(TokenHandler)来进行表达式的处理
        //参数：openToken(开始标记)，closeToken(结束标记)，handler(标记处理器)
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        //#{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }

    public static boolean isBaseType(Class<?> clazz) {
        if (clazz.equals(java.lang.Integer.class) ||
                clazz.equals(java.lang.Byte.class) ||
                clazz.equals(java.lang.Long.class) ||
                clazz.equals(java.lang.Double.class) ||
                clazz.equals(java.lang.Float.class) ||
                clazz.equals(java.lang.Character.class) ||
                clazz.equals(java.lang.Short.class) ||
                clazz.equals(java.lang.Boolean.class)) {
            return true;
        }
        return false;
    }
}
